//
//  AzkarDeatailController.m
//  Azkar
//
//  Created by 王易 on 2018/8/24.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "AzkarDeatailController.h"
#import "AzkarDeatailCell.h"
#import "AzkariCarouselView.h"
#import "NetworkManagerV3.h"
#import "AzkarApi.h"
#import "SendAzkarController.h"
#import "PrayViewController.h"

/**
 祈福列表详情页
 */
@interface AzkarDeatailController ()<UITableViewDelegate, UITableViewDataSource, RefreshDelegate>

@property (nonatomic, strong) NSMutableArray *dataModel;

@property (nonatomic,weak) RefreshTableView *tableView;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic,weak) AzkariCarouselView *carousel;

@property (nonatomic, strong) NSIndexPath *indexP;
@property (nonatomic) BOOL isRefresh;

@end

@implementation AzkarDeatailController
- (NSMutableArray *)dataModel
{
    if (!_dataModel) {
        _dataModel = [NSMutableArray array];
    }
    return _dataModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initUI];
    //
    WeakSelf
    [[[NSNotificationCenter defaultCenter]rac_addObserverForName:AppLanguageChangedNotification object:nil]subscribeNext:^(id x) {
//        StrongSelf
//        if ([[LanguageManager defaultManager].appLanguage isEqualToString:@"ar"]) {
//            [MyBaseLayout setIsRTL:YES];
//        }else{
//            [MyBaseLayout setIsRTL:NO];
//        }
//        [self.tableView reloadData];
    }];
    if (@available(iOS 9.0, *)) {
        if ([UIView appearance].semanticContentAttribute == UISemanticContentAttributeForceRightToLeft) {
            [MyBaseLayout setIsRTL:YES];
        }
    } else {
        // Fallback on earlier versions
    }
    [[[NSNotificationCenter defaultCenter]rac_addObserverForName:SendAzkarSuccess_Const object:nil]subscribeNext:^(id x) {
        StrongSelf
       self.tableView.isRefreshing = YES;
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    
}

- (void)initUI
{
    
    MyRelativeLayout *rootLayout = [MyRelativeLayout new];
    rootLayout.myBottom = 0;
    rootLayout.myTop = 0;
    rootLayout.myHorzMargin= 0;
    rootLayout.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:rootLayout];
    
    RefreshTableView *tableView = [[RefreshTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.myMargin = 0;
    tableView.estimatedRowHeight = 44;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.backgroundColor = Color(@"#F7F7F7");
    self.view.backgroundColor = Color(@"#F7F7F7");
    self.tableView = tableView;
    [rootLayout addSubview:tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.refreshDelegate = self;
    self.tableView.canHeaderRefresh = YES;
    self.tableView.canFooterRefresh = YES;
    self.tableView.isRefreshing = YES;
    [AzkarDeatailCell registerNibToTable:self.tableView];
    
    AzkariCarouselView *carousel = [AzkariCarouselView new];
    self.carousel = carousel;
    self.tableView.tableHeaderView = carousel;
    self.tableView.tableHeaderView.height = (ScreenWidth * 9 / 16);
    
    WeakSelf
    // 刷新
    [[[NSNotificationCenter defaultCenter]rac_addObserverForName:AzkarComments_Const object:nil]subscribeNext:^(id x) {
        StrongSelf
        if (self.indexP) {
            [self.tableView reloadRowAtIndexPath:self.indexP withRowAnimation:0];
        }
    }];
    
    UIButton *add = [UIButton buttonWithType:UIButtonTypeCustom];
    add.myWidth = 56;
    add.myHeight = 60;
    add.myBottom = 22+TabbarHeight;
    add.myTrailing = 20;
    [add changeBackgroundImage:Image(@"send_btn")];
    [rootLayout addSubview:add];
    [add setHyb_onTouchUp:^(UIButton *sender) {
//        RouteToPage(@"SendAzkarController");
        [FIRAnalytics logEventWithName:@"du_click_add"
                            parameters:nil];
        if ([AppDataManager sharedManager].isLogin) {
            SendAzkarController *c = [SendAzkarController new];
            c.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:c animated:YES];
        }
        else{
            Class c = NSClassFromString(@"LoginController");
            if (c) {
                UIViewController *ctr = [c new];
                ctr.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:ctr animated:YES];
            }
        }
    }];
}
- (void)loadData
{
    NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:@{@"limit":@"10",@"offset":[NSString stringWithFormat:@"%ld",self.pageIndex * 10 ]}];
    if (self.top) {
        [parms setObject:self.top forKey:@"top"];
    }
    [[AzkarApi getData:BlessBlog withParm:parms]subscribeNext:^(id x) {
        
        self.tableView.isRefreshing = NO;
        self.tableView.isLoadingMoreData = NO;
        if (self.isRefresh) {
            [self.dataModel removeAllObjects];
            self.isRefresh = NO;
        }
        AzkarModel *model = [AzkarModel yy_modelWithDictionary:x];
        
        [self.dataModel addObjectsFromArray:model.bless];
        
        if (model.bless.count < 10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            self.pageIndex ++ ;
        }
        
        if (model.public_bless.count > 0) {
            self.carousel.public_bless = model.public_bless;
        }
        [self.tableView reloadData];
        
    } error:^(NSError *error) {
        self.isRefresh = NO;
        self.tableView.isRefreshing = NO;
        self.tableView.isLoadingMoreData = NO;
        
    }];
}

- (void)onRefreshing:(id)control {
    if (self.isRefresh) {
        return;
    }
    self.pageIndex = 0;
    
    [self.tableView.mj_footer resetNoMoreData];
    
//    [self.dataModel removeAllObjects];
    self.isRefresh = YES;
    
    [self loadData];
}
- (void)onLoadingMoreData:(id)control {
    [self loadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataModel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AzkarDeatailCell *cell = [tableView dequeueReusableCellWithIdentifier:[AzkarDeatailCell reuseIdentifier]];
    
    cell.blessModel = self.dataModel[indexPath.row];
    cell.isTop = self.top?YES:NO;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.indexP = indexPath;
//    RouteToPageWithInfo(@"PrayViewController", @{@"blessModel":self.dataModel[indexPath.row]});
    PrayViewController *c = [PrayViewController new];
    c.blessModel = self.dataModel[indexPath.row];
    c.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:c animated:YES];
    NSDictionary *dic;
    if (self.top) {
        dic = @{@"top_commentid":c.blessModel.ID,@"top_comment":c.blessModel.cnt_comment};
    }
    else{
        dic = @{@"new_commentid":c.blessModel.ID,@"new_comment":c.blessModel.cnt_comment};
    }
    [FIRAnalytics logEventWithName:@"a_click_comment"
                        parameters:dic];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
